//
//  NewsListViewController.m
//  GolfFriend
//
//  Created by Vescky on 14-5-2.
//  Copyright (c) 2014年 vescky.org. All rights reserved.
//

#import "NewsListViewController.h"
#import "AdView.h"
#import "AdViewData.h"
#import "CacheDaoForfficalNews.h"
#import "AppsEngine.h"
#import "GFVOParser.h"
#import "SVProgressHUD.h"
#import "UserSession.h"
#import "WebAppsConstant.h"
#import "NewsDetailViewController.h"
#import "AppDelegate.h"
#import "NewsCell.h"

@interface NewsListViewController ()<UITableViewDataSource,UITableViewDelegate> {
    NSMutableArray *dataSource;
    AdView *aView;
    NSString *currentIndex;
    UITableViewCell *headerCell;
}
@end

@implementation NewsListViewController
@synthesize newsType;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    if (newsType == 0) {
        self.title = @"活动资讯";
    }
    else if (newsType == 1) {
        self.title = @"高端品鉴";
    }
    
    [self.navigationController.navigationBar setHidden:NO];
    [super customBackButton];
    [self initView];
    [self initData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Private
- (void)initView {
//    CGRect tbRect = tbView.frame;
//    if (iPhone5) {
//        tbRect.size.height = 454.f;
//    }
//    else {
//        tbRect.size.height = 366.f;
//    }
//    if (!ShowToolbarInWindow) {
//        tbRect.size.height = tbRect.size.height + 50;
//    }
//    
//    [tbView setFrame:tbRect];
    tbView.delegate = self;
}

- (void)initData {
    //读取缓存数据，再请求网上数据
    NSMutableArray *cDataArray = [[CacheDaoForfficalNews shareCacheDaoForfficalNews] getCacheDataLimitRow:NSMakeRange(0, 20) newsType:newsType];
    if (cDataArray && [cDataArray count] > 0) {
        if (dataSource) {
            [dataSource removeAllObjects];
        }
        dataSource = cDataArray;
        [tbView reloadData];
    }
//    [self getDataFromServer];
    [self refreshData];
}

- (void)getDataFromServer {
    NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:currentIndex,@"articleId",
                                   [[UserSession shareUserSession] getUserId],@"userId", nil];
    
    if (newsType == 1) {
        [params setObject:@"1" forKey:@"newsType"];
    }
    
    //网上请求数据
    [[AppsEngine shareAppsEngine] submitRequest:@"gfGetNewsList" param:params onCompletion:^(id jsonResponse) {
        if ([jsonResponse objectForKey:@"status"] && [[jsonResponse objectForKey:@"status"] isEqualToString:@"success"]) {
            NSLog(@"刷新成功");
            [tbView setHidden:NO];
            if ([currentIndex isEqualToString:Initial_index]) {
                [SVProgressHUD showSuccessWithStatus:@"刷新成功"];
            }
            
            NSMutableArray *arr1 = [jsonResponse objectForKey:@"list"];
            if ([arr1 respondsToSelector:@selector(count)] && [arr1 count] > 0) {
                [self addObjectsFromArrayByDeletingSameItem:arr1];//结果加入dataSource中，去掉重复记录
                NSDictionary *newestItem = [dataSource lastObject];
                if ([newestItem objectForKey:@"id"]) {
                    currentIndex = [newestItem objectForKey:@"id"];
                }
                [[CacheDaoForfficalNews shareCacheDaoForfficalNews] updateCacheDataWithNewsContentArray:dataSource];
                [tbView reloadData];
            }
            else {
                if ([dataSource count] < 1) {
                    //无内容
                    [tbView setHidden:YES];
                }
                else {
                    if (![currentIndex isEqualToString:Initial_index]) {
                        [SVProgressHUD showSuccessWithStatus:@"没有更多内容了!"];
                    }
                }
            }
        }
        else {
            if ([dataSource count] < 1) {
                //无内容
                [tbView setHidden:YES];
            }
            else {
                if (![currentIndex isEqualToString:Initial_index]) {
                    [SVProgressHUD showSuccessWithStatus:@"没有更多内容了!"];
                }
            }
        }
        [super endRefreshing];
    } onError:^(NSError *error) {
        NSLog(@"联网失败");
        [super endRefreshing];
        if ([dataSource count] < 1) {
            //无内容
            [tbView setHidden:YES];
        }
        else {
            if (![currentIndex isEqualToString:Initial_index]) {
                [SVProgressHUD showSuccessWithStatus:@"没有更多内容了!"];
            }
        }
    } method:@"GET"];
}

- (void)addObjectsFromArrayByDeletingSameItem:(NSMutableArray*)arr {
    if (!arr || [arr count] < 1) {
        return;
    }
    if (!dataSource) {
        dataSource = [[NSMutableArray alloc] init];
    }
    for (int i = 0; i < [arr count]; i++) {
        NSString *newId = [[arr objectAtIndex:i] objectForKey:@"id"];
        bool isSameItem = NO;
        for (int j = 0; j < [dataSource count]; j++) {
            NSString *d_newId = [[dataSource objectAtIndex:j] objectForKey:@"newsId"];
//            if (!d_newId || d_newId.length < 1) {
//                d_newId = [[arr objectAtIndex:i] objectForKey:@"id"];
//            }
            if ([d_newId isEqualToString:newId]) {
                //相同的
                isSameItem = YES;
                break;
            }
        }
        
        if (!isSameItem) {
            [dataSource addObject:[arr objectAtIndex:i]];
        }
    }
}


- (void)initAdVeiw {
    NSMutableArray *arr = [[NSMutableArray alloc] init];
    if ([dataSource count] > 5) {
        arr = [[NSMutableArray alloc] initWithArray:[dataSource subarrayWithRange:NSMakeRange(0, 5)]];
    }
    else {
        arr = dataSource;
    }
    
    if ([arr count] < 1) {
        return;
    }
    
    NSMutableArray *aDataSource = [[NSMutableArray alloc] init];
    for (int i = 0; i < [arr count]; i++) {
        NSDictionary *content = [arr objectAtIndex:i];
        if (isValidDictionary([content objectForKey:@"sourceLinks"])) {
            NSArray *imgs = [[content objectForKey:@"sourceLinks"] objectForKey:@"image"];
            
            AdViewData *aData = [[AdViewData alloc] init];
            aData.adWords = [content objectForKey:@"title"];
            aData.webImageLink = [imgs count] > 0 ? [imgs objectAtIndex:0] : nil;
            aData.tag = i;
            aData.recordId = [[content objectForKey:@"newsId"] integerValue] ? [[content objectForKey:@"newsId"] integerValue] : [[content objectForKey:@"id"] integerValue];
            [aDataSource addObject:aData];
        }
    }
    
    if (!aView) {
       aView = [[AdView alloc] init];
        [aView setFrame:CGRectMake(0.f, 0.f, 320.f, 180.f)];
    }
    [aView setSourceArr:aDataSource];
    [aView loadAds];
}


- (void)setNewsListType:(NSNumber*)nType {
    newsType = [nType intValue];
}

#pragma mark - over write
- (void)refreshData {
    currentIndex = Initial_index;
    [self getDataFromServer];
}

- (void)loadMoreData {
    [self getDataFromServer];
}


#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if ([dataSource count] < 4) {
        return 1;
    }
    return [dataSource count] - 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"NewsCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (indexPath.row == 0) {
        //展示图片
        headerCell = [[UITableViewCell alloc] initWithFrame:CGRectMake(0, 0, 320, 180)];
        [self initAdVeiw];
        [headerCell.contentView addSubview:aView];
        [aView loadAds];
        return headerCell;
    }
    
    if(!cell){
        cell = [[[NSBundle mainBundle] loadNibNamed:@"NewsCell" owner:self options:nil] objectAtIndex:0];
    }
    
    if([cell respondsToSelector:@selector(setCellData:)]){
        [cell performSelector:@selector(setCellData:) withObject:[dataSource objectAtIndex:indexPath.row + 4]];
    }
    if([cell respondsToSelector:@selector(setDelegate:)]){
        [cell performSelector:@selector(setDelegate:) withObject:self];
    }
    
    [cell setTag:indexPath.row];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return 180.f;
    }
    else {
        return 100.f;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return;
    }
    if (indexPath.row + 4 > [dataSource count]) {
        return;
    }
    NSDictionary *dict = [dataSource objectAtIndex:indexPath.row + 4];
    int _recordId = [[dict objectForKey:@"id"] integerValue];
    if (!_recordId) {
        _recordId = [[dict objectForKey:@"newsId"] integerValue];
    }
    NSString *wLink = Webapp_News_Detail_Link(_recordId);
    NewsDetailViewController *ndViewController = [[NewsDetailViewController alloc] init];
    ndViewController.webappLink = wLink;
    ndViewController.detailInfo = dict;
    ndViewController.recordId = [dict objectForKey:@"id"];
    ndViewController.coverImage = [(NewsCell*)[tbView cellForRowAtIndexPath:indexPath] imgv].image;
    [[APP_DELEGATE navigationController] pushViewController:ndViewController animated:YES];
    NSLog(@"link: %@", wLink);
    [tbView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

@end
